import requests
import json
import pandas as pd

def geocode_geo(key,address,city=None,batch="false",sig=None,output="json",callback=None):
    """获取高德地图API的地理编码：
       将详细的结构化地址转换为高德经纬度坐标。
       且支持对地标性名胜景区、建筑物名称解析为高德经纬度坐标。"""

    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    params = {
        "key":key,
        "address":address,
        "city":city,
        "batch":batch,
        "sig":sig,
        "output":"json",
        "callback":callback
            }
    r = requests.get(url,params=params)
    result = r.json()['geocodes'][0]['location']
    return result


def geocode_regeo(key,location,poitype=None,radius=1000,extensions="base",batch="false",roadlevel=None,sig=None,output="json",callback=None,homeorcorp=0):
    """获得高德地图的逆地理编码：
       将经纬度转换为详细结构化的地址"""

    regeo_url = 'https://restapi.amap.com/v3/geocode/regeo?parameters'
    params = {
        "key":key,
        "location":location,
        "poitype":poitype,
        "radius":radius,
        "extensions":extensions,
        "batch":batch,
        "roadlevel":roadlevel,
        "sig":sig,
        "output":output,
        "callback":callback,
        "homeorcorp":homeorcorp
        }
    r = requests.get(regeo_url,params=params)
    result = r.json()['regeocode']['formatted_address']
    return result


def direction_walking(key,origin,destination,sig=None,output="json",callback=None):
    """获得高德的路径规划（步行）：
       输入起始点与终止点即获得步行方案的动作指令"""
    
    walking_url = 'https://restapi.amap.com/v3/direction/walking?parameters'
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "sig":sig,
        "output":output,
        "callback":callback
   }
    r = requests.get(walking_url ,params=params)
    walk_msg = r.json()['route']['paths'][0]['steps']
    for i in walk_msg: #先用for循环遍历出list其中所有元素（list中的每一个字典都算一个元素）
        print(i.get('instruction'))
       


def direction_transit(key,origin,destination,city,cityd=None,extensions="base",strategy=0,nightflag=0,date=None,time=None,sig=None,output="json",callback=None):
    """获得高德的路径规划（公交车）：
       输入起点、终点、所在城市（若跨城则需要分别输入起点与终点所在的城市）
       即得到综合各类公共（火车、公交、地铁）交通方式的通勤方案"""
    transit_url = 'https://restapi.amap.com/v3/direction/transit/integrated?parameters'
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "city":"广州",
        "cityd":cityd,
        "extensions":extensions,
        "strategy":strategy,
        "nightflag":nightflag,
        "date":date,
        "time":time,
        "sig":sig,
        "output":output,
        "callback":callback
    }
    
    r = requests.get(transit_url ,params=params)
    
    count = r.json()["count"] # 返回的方案数
    for i in range(0,int(count)):
        print("线路:",i+1)
        bus_name=r.json()["route"]["transits"][i]["segments"][0]["bus"]["buslines"][0]["name"]
         
        print("公交车线路名称：",bus_name)
        walking_distance=r.json()["route"]["transits"][i]["walking_distance"]

        print("步行距离:",walking_distance)
        departure_stop=r.json()["route"]["transits"][i]["segments"][0]["bus"]["buslines"][0]["departure_stop"]["name"]

        print("起始站：",departure_stop)
        arrival_stop=r.json()["route"]["transits"][i]["segments"][0]["bus"]["buslines"][0]["arrival_stop"]["name"]

        print("终点站：",arrival_stop)
        print("-------------------------------------------")




def district(key,keywords,subdistrict=1,page=1,offset=20,extensions='base',filter=None,output="json",callback=None):
    """获得高德的行政区域查询：
       输入关键字，可以查找特定的行政区域信息。（比如搜索省份可显示市、区）"""
    district_url = 'https://restapi.amap.com/v3/config/district?parameters'
    params = {
        "key":key,
        "keywords":keywords,
        "subdistrict":subdistrict,
        "page":page,
        "offset":offset,
        "extensions":extensions,
        "filter":filter,
        "callback":callback,
        "output":output     
    }
    r = requests.get(district_url,params=params)
    print(pd.json_normalize(r.json()['districts'][0]['districts']))




def place(key,keywords,city,types=None,citylimit="false",children=0,offset=20,page=1,extensions='all',sig=None,output="json",callback=None):
    """获取高德搜索POI：
       通过用POI的关键字进行条件搜索，例如：肯德基、朝阳公园等；同时支持设置POI类型搜索，例如：银行"""
    place_url = 'https://restapi.amap.com/v3/place/text?parameters'
    params = {
        "key":key,
        "keywords":keywords,
        "types":types,
        "city":city,
        "citylimit":citylimit,
        "children":children,
        "offset":offset,
        "page":page,
        "extensions":extensions,  
        "sig":sig,
        "output":"json",
        "callback":callback
        }
    r = requests.get(place_url,params=params)
    count = r.json()["count"]
    for i in range(0,int(count)):
        name = r.json()["pois"][i]['name']
        print("名称：",name)
        address = r.json()["pois"][i]['address']
        print("地址：",address)
        #parking_type = r.json()["pois"][i]['parking_type']
        biz_ext = r.json()["pois"][i]['biz_ext']
        print("有关信息：",biz_ext)
        print("______________________________________________________________")



def IP(key,ip=None,sig=None,output="json"):
    """获得高德的IP定位：
       根据用户输入的IP地址，能够快速的帮用户定位IP的所在位置。
       若用户不填写IP，则取客户http之中的请求来进行定位"""
    ip_url = 'https://restapi.amap.com/v3/ip?parameters'
    params = {
        "key":key,
        "ip":ip, 
        "sig":sig,
        "output":"json",

    }
    r = requests.get(ip_url,params=params)
    province = r.json()['province']
    city = r.json()['city']

    print("IP地址所在地:",province,city)





def staticmap(key,location,zoom,size="400*400",markers=None,labels=None,paths=None,traffic=0,sig=None):
    """获得高德的静态地图：
          输入key、地图中心点坐标、地图级别
          使用户能够将高德地图以图片形式嵌入自己的网页中
          用户还可以指定请求的地图位置、图片大小、以及在地图上添加覆盖物，如标签、标注、折线、多边形。"""
        
    url='https://restapi.amap.com/v3/staticmap?parameters'
    params={
        "key":key,
        "location":location,
        "zoom":zoom,
        "size":size,
        "markers":markers,
        "labels":labels,
        "paths":paths,
        "traffic":traffic,
        "sig":sig
    }
    r =  requests.get(url,params=params)
    results = Image.open(BytesIO(r.content)) 
    return results



def coordinate(key,locations,coordsys="autonavi",sig=None,output="json"):
    """获得高德的坐标转化：
       将用户输入的非高德坐标（GPS坐标、mapbar坐标、baidu坐标）转换成高德坐标。"""
    
    convert_url = 'https://restapi.amap.com/v3/assistant/coordinate/convert?parameters'
    params = {
        "key":key,
        "locations":locations,
        "coordsys":coordsys,
        "sig":sig,
        "output":output

    }
    r = requests.get(convert_url,params=params)
    result = r.json()['locations']
    return result




def batch():
    """获得高德API的批量请求接口：
       批量接口通过用户传入合并后的请求，同时返回多个请求的顺序集合，目前最多支持20个子请求。 返回的顺序与子请求的顺序一致。"""
    batch_url = 'https://restapi.amap.com/v3/batch?parameters'
   
    params = {
        "key":key
    }
    body = {
        
        "ops": [
            {
                "url": "/v3/place/around?offset=10&page=1&key='cddee357dd2e2bb7bf9df9bc69652238'&location=116.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
            },
            {
                "url": "/v3/place/around?offset=10&page=1&key='cddee357dd2e2bb7bf9df9bc69652238'&location=118.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
            }
        ]
    }
   
    
    r = requests.get(batch_url,params=params,json=body)
    result = r.json()
    return result







def weatherInfo(key,city,extensions=None,output="json"):
    """获取高德的天气查询：
       根据用户输入的adcode，查询目标区域当前/未来的天气情况。"""
    
    weatherInfo_url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
    params = {
        "key":key,
        "city":city,
        "extensions":extensions,
        "output":output
       
    }
    r = requests.get(weatherInfo_url,params=params)
    result = r.json()['lives']
    return result





def inputtips(key,keywords,type,location=None,city=None,citylimit='false',datatype="all",sig=None,output="json",callback=None):
    """获得高德的输入提示：
       提供根据用户输入的关键词查询返回建议列表"""
    
    inputtips_url = 'https://restapi.amap.com/v3/assistant/inputtips?parameters'
    params = {
        "key":key,
        "keywords":keywords,
        "type":type,
        "location":location,
        "city":city,
        "citylimit":citylimit,
        "datatype":datatype,
        "sig":sig,
        "output":output,
        "callback":callback

    }
    r = requests.get(inputtips_url,params=params)
    # 得出列表中有几个元素
    num_list = len(r.json()['tips'])
    # 遍历出列表嵌套的每个字典里的同名信息
    for i in range(1,num_list):
        name_msg = r.json()['tips'][i]['name']
        address_msg = r.json()['tips'][i]['address']
        print(name_msg)
        print(address_msg)
        print("--------------------------------")
